import java.sql.*;
import java.util.Scanner;

public class a {
    public static void main(String[] args) {

       m5();
        //1、 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8",
                    "root","2333");

            if (conn!=null){
                System.out.println("连接成功");
            }

            //3、编写sql语句
            String sql = "select * from sys_user";

            //4、预处理sql  .var
            PreparedStatement preparedStatement = conn.prepareStatement(sql);

            //5、如果有参数，设置参数

            //6、执行sql语句
            ResultSet resultSet = preparedStatement.executeQuery();

            // 7、如果是查询就遍历结果/如果是增删改 判断是否成功
            while (resultSet.next()) {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String pass = resultSet.getString(3);
                System.out.println(id+"------"+name+"-------"+pass);
            }

            //关闭资源
            resultSet.close();
            preparedStatement.close();
            conn.close();
            
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    private static void m5() {
        //1、 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2、获取连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8",
                    "root", "2333");

            if (conn != null) {
                System.out.println("连接成功");
            }

            //3、编写sql语句
            String sql = "UPDATE sys_user SET name = ? WHERE name = ?";

            //4、预处理sql  .var
            PreparedStatement preparedStatement = conn.prepareStatement(sql);

            //5、如果有参数，设置参数
            preparedStatement.setString(1, "ad");  // 新的id值
            preparedStatement.setString(2, "admin");  // 要修改的id

            //6、执行sql语句
            int result = preparedStatement.executeUpdate();

            // 7、如果是查询就遍历结果/如果是增删改 判断是否成功
            if (result > 0) {
                System.out.println("修改成功");
            } else {
                System.out.println("没有找到要修改的数据");
            }

            //关闭资源

            preparedStatement.close();
            conn.close();

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException( e);
        }
    }
}

